<?php

/**
 * 自定义函数
 */

//定义全局ret
defined('RET_OK') or define('RET_OK', 0);
defined('RET_SUCCESS_MSG') or define('RET_SUCCESS_MSG', "success");
defined('RET_ERROR') or define('RET_ERROR', -1);
defined('RET_BIND_PHONE') or define('RET_BIND_PHONE', 1000);
defined('RET_WECHAT_AUTH') or define('RET_WECHAT_AUTH', 1001);

if (!function_exists('api'))
{

    /**api 统一返回格式，传递参数个数不同时，按以下逻辑接收
     * 0：返回错误，信息提示"ERROR"
     * 1：返回错误，信息为所传参数1
     * 2：返回错误，参数1为信息，参数2为数据
     * 3: 参数1为结果码，参数2为信息，参数3为数据
     * 4或4以上: 只考虑前3个
     *
     * @param array ...$args
     * @return array
     */
    function api(...$args)
    {
        if (!isset($args[2]))
        {
            //参数少于3个时，默认为错误状态。
            $ret = RET_ERROR;
            $msg = isset($args[0]) ? $args[0] : 'ERROR';
            $data = isset($args[1]) ? $args[1] : [];
        }
        else
        {
            $ret = $args[0];
            $msg = $args[1];
            $data = $args[2];
        }
        if ($data instanceof \Illuminate\Http\Resources\Json\ResourceCollection || $data instanceof \Illuminate\Http\Resources\Json\JsonResource)
        {
            $data = $data->response()->getData(true);
            if (isset($data['data']) && count($data) == 1)
            {
                //单纯的集合，无分页等其数据
                $data = $data['data'];
            }
        }

        return [
            'ret' => (int)$ret,
            'msg' => (string)$msg,
            'data' => $data,
            'timeuse' => (float)number_format(microtime(true) - LARAVEL_START, 3),
        ];
    }
}
if (!function_exists('generate_order_no'))
{
    /**
     * 生成唯一订单号
     * @return mixed
     */
    function generate_order_no()
    {
        mt_srand((double) microtime() * 1000000);

//        return date('Ymd') . str_pad(mt_rand(1, 99999), 6, '0', STR_PAD_LEFT).getmypid();
        return "XXK".date('Ymd') . str_pad(mt_rand(1, 999), 3, '0', STR_PAD_LEFT).str_pad(getmypid(),3,'0').time();
    }
}

if (!function_exists('generate_random_int'))
{
    /**
     * 生成随机数字串
     * @return mixed
     */
    function generate_random_int($num = 9)
    {
        $re = '';
        $s = '0123456789';
        while( strlen($re) < $num ) {
            $re .= $s[rand(0, strlen($s)-1)];
        }
        return $re;
    }
}

if (!function_exists('checkBankCard'))
{
    /**
     * 验证银行卡号码格式
     * @param string $id_card 银行卡号码
     * @return boolean
     */
    /**
     * 验证银行卡号
     * @param  string $bankCardNo 银行卡号
     * @return bool             是否合法(true:合法,false:不合法)
     */
    function checkBankCard($bankCardNo)
    {
        $strlen = strlen($bankCardNo);
        if($strlen < 15 || $strlen > 19)
        {

            return false;
        }

        if (!preg_match("/^\d{15}$/i",$bankCardNo) && !preg_match("/^\d{16}$/i",$bankCardNo) &&
            !preg_match("/^\d{17}$/i",$bankCardNo) && !preg_match("/^\d{18}$/i",$bankCardNo) &&
            !preg_match("/^\d{19}$/i",$bankCardNo))
        {

            return false;
        }

        $arr_no = str_split($bankCardNo);
        $last_n = $arr_no[count($arr_no)-1];
        krsort($arr_no);
        $i = 1;
        $total = 0;
        foreach ($arr_no as $n)
        {
            if($i%2==0)
            {
                $ix = $n*2;
                if($ix>=10)
                {
                    $nx = 1 + ($ix % 10);
                    $total += $nx;
                }
                else
                {
                    $total += $ix;
                }
            }
            else
            {
                $total += $n;
            }
            $i++;
        }
        $total -= $last_n;
        $x = 10 - ($total % 10);
        if($x != $last_n)
        {

            return false;
        }

        return true;
    }
}



if (!function_exists('substr_cut'))
{
    /**
     * 替换中文汉字
     * @param $user_name
     * @return string
     */
    function substr_cut($user_name)
    {
        $strlen = mb_strlen($user_name, 'utf-8');
        $firstStr = mb_substr($user_name, 0, 1, 'utf-8');
        $lastStr = mb_substr($user_name, -1, 1, 'utf-8');
        return $strlen == 2 ? $firstStr . str_repeat('*', mb_strlen($user_name, 'utf-8') - 1) : $firstStr . str_repeat("*", $strlen - 2) . $lastStr;
    }
}

if (!function_exists('imageUrl'))
{
    /**
     * 生成图片网址
     *
     * @param $key
     * @param string $options
     * @return string
     */
    function imageUrl($key, $options = '')
    {
        if (substr($key, 0, 4) == 'http')
        {
            if (!$options)
            {
                return $key;
            }
            return sprintf("%s?x-oss-process=image/%s", $key, trim($options, '/'));
        }
        $driver = config('filesystems.default');
        if ($driver == 'oss')
        {
            $config = config('filesystems.disks.oss');
            //@see https://github.com/jacobcyl/Aliyun-oss-storage/blob/master/src/AliOssAdapter.php#L571
            $url = ( $config['ssl'] ? 'https://' : 'http://' ) . ( $config['isCName'] ? ( $config['cdnDomain'] == '' ? $config['endpoint'] : $config['cdnDomain'] ) : $config['bucket'] . '.' . $config['endpoint'] ) . '/' . ltrim($key, '/');
            if (!$options)
            {
                return $url;
            }
            return sprintf("%s?x-oss-process=image/%s", $url, trim($options, '/'));
        }
        elseif ($driver == 'qiniu')
        {
            $url = \Storage::url($key);
            if (!$options)
            {
                return $url;
            }
            return sprintf("%s?imageView2/%s", $url, trim($options, '/'));
        }
        else
        {
            return \Storage::url($key);
        }

    }
}

if (!function_exists('graphicImageUrl'))
{
    /**
     * 生成图片网址
     *
     * @param $key
     * @param string $options
     * @return string
     */
    function graphicImageUrl($key, $options = '')
    {
        if (substr($key, 0, 4) == 'http')
        {
            if (!$options)
            {
                return $key;
            }
            return sprintf("%s?x-oss-process=image/%s", $key, trim($options, '/'));
        }

        $config = config('filesystems.disks.admin');
        //@see https://github.com/jacobcyl/Aliyun-oss-storage/blob/master/src/AliOssAdapter.php#L571
        $url = ( $config['ssl'] ? 'https://' : 'http://' ) . ( $config['isCName'] ? ( $config['cdnDomain'] == '' ? $config['endpoint'] : $config['cdnDomain'] ) : $config['bucket']  ) . '/' . ltrim($key, '/');
        if (!$options)
        {
            return $url;
        }
        return sprintf("%s?x-oss-process=images/%s", $url, trim($options, '/'));
    }
}

if (!function_exists('createdAt'))
{
    /**
     * 获取创建时间，过去的时间在一定范围内，显示xx小时前之类，太过久远就直接显示时间
     *
     * @param $time 创建时间
     * @param string $format 太过久远时显示时间的格式，默认Y-m-d H:i
     * @param string $interval “久远”是多久，默认10天
     * @return string
     */
    function createdAt($time, $format = 'Y-m-d H:i', $interval = "P10D")
    {
        $pivot = \Carbon\Carbon::now()->sub(new \DateInterval($interval));
        $target = $time instanceof \Carbon\Carbon ? $time : \Carbon\Carbon::createFromTimestamp(strtotime($time));
        $diff = $pivot->diff($target);
        //如果时间过于久远（超出 diff 指定的时间），直接显示具体时间
        if ($diff->invert)
        {
            return $target->format($format);
        }
        return $target->diffForHumans();

    }
}


if (!function_exists('formListUrl'))
{
    /**
     * 获取 form 表单右上角的“列表”
     * @param $url
     * @return string
     */
    function formListUrl($url)
    {
        return sprintf('<a href="%s" class="btn btn-sm btn-default" title="列表"><i class="fa fa-list"></i><span class="hidden-xs">&nbsp;列表</span></a>', $url);
    }
}



